<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isHaveMobile ? $t('allinpay.untapePhone') : $t('allinpay.beTiedPhone')"
    :close-on-click-modal="false"
    :append-to-body="true"
    :width="$t('language')==='English'?'450px':'378px'"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="rules"
      :label-width="$t('language')==='English'?'128px':'64px'"
      @submit.prevent
    >
      <el-form-item
        prop="mobile"
        :label="$t('allinpay.mobile')"
      >
        <el-input
          v-model="dataForm.mobile"
          :placeholder="$t('allinpay.pleaseEnterPhone')"
          :disabled="isHaveMobile"
          style="width: 274px;"
          maxlength="11"
          @input="(val)=>{ dataForm.mobile=val.replace(/[^\d]/g,'') }"
        >
          <template
            v-if="countdown===0"
            #suffix
          >
            <div
              class="get-code"
              @click="onGetCode"
            >
              {{ $t('allinpay.getCode') }}
            </div>
          </template>
          <template
            v-else
            #suffix
          >
            <div class="get-code">
              {{ countdown }} s
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        prop="validCode"
        :label="$t('allinpay.code')"
      >
        <el-input
          v-model="dataForm.validCode"
          :placeholder="$t('allinpay.pleaseEnterCode')"
          style="width: 274px;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="dialogVisible = false">
          {{ $t('allinpay.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit"
        >
          {{ isHaveMobile?$t('allinpay.unbinding'):$t('allinpay.binding') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { isMobile } from '@/utils/validate'
import { Debounce } from '@/utils/debounce'

const emit = defineEmits(['refreshDataForm'])
const props = defineProps({
  // 是否拥有（已绑定）手机号
  isHaveMobile: {
    default: false,
    type: Boolean
  }
})

const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error($t('allinpay.InputCorrectPhone')))
  } else {
    callback()
  }
}
const rules = reactive({
  mobile: [
    { required: true, message: $t('allinpay.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  validCode: [
    { required: true, message: $t('allinpay.capNoNull'), trigger: 'blur' }
  ]
})

const dataFormRef = ref(null)
const dialogVisible = ref(false)
const dataForm = reactive({
  mobile: '', // 手机号
  validCode: ''
})
const init = (mobile) => {
  dialogVisible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    dataForm.mobile = mobile || null
  })
}

/**
 * 绑定或解绑手机号
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const data = {
      phone: dataForm.mobile,
      verificationCode: dataForm.validCode
    }
    const url = props.isHaveMobile ? '/shop/allinpay/company/unbindPhone' : '/shop/allinpay/company/bindPhone'
    http({
      url: http.adornUrl(url),
      method: props.isHaveMobile ? 'put' : 'post',
      data: http.adornData(data)
    }).then(() => {
      ElMessage({
        message: $t('allinpay.saveSuccess'),
        type: 'success',
        duration: 1000
      })
      dialogVisible.value = false
      emit('refreshDataForm')
      dataFormRef.value?.resetFields()
    })
  })
}, 1500)
/**
 * 获取验证码
 */
let countdown = ref(0) // 倒计时
const onGetCode = Debounce(() => {
  if (!isMobile(dataForm.mobile)) {
    ElMessage({
      message: $t('allinpay.InputCorrectPhone'),
      type: 'error',
      duration: 1000
    })
    return
  }
  const data = {
    phone: dataForm.mobile,
    verificationCodeType: props.isHaveMobile ? 6 : 9
  }
  http({
    url: http.adornUrl('/shop/allinpay/company/sendVerificationCode'),
    method: 'post',
    data: http.adornData(data)
  }).then(() => {
    countdown.value = 60
    onGetCountdown()
  }).catch((e) => {})
})

let timer = ''
const onGetCountdown = () => {
  timer = setInterval(() => {
    countdown--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}
defineExpose({
  init
})
</script>

<style scoped>
  .get-code {
    font-size: 14px;
    line-height: 18px;
    color: #155BD4;
    margin-right: 7px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    height: 100%;
  }
  :deep(.el-dialog__header) {
    border-bottom: 1px solid rgba(0,0,0,0.06);
  }
  :deep(.el-dialog__footer) {
    border-top: 1px solid rgba(0,0,0,0.06);
    padding-bottom: 10px;
  }
</style>
